var http = require('https');
var fs = require('fs');
var cheerio = require('cheerio');
var url = "https://www.biedoul.com/article/163190"

startRequest(url);

function startRequest(x) {
  //采用http模块向服务器发起一次get请求      
  http.get(x, function (res) {
    //用来存储请求网页的整个html内容
    var html = '';
    //防止中文乱码  
    res.setEncoding('utf-8'); 
    // 监听data事件，每次取一块数据
    res.on('data', function (chunk) {
      html += chunk;
    });
    //监听end事件，如果整个网页内容的html都获取完毕，就执行回调函数
    res.on('end', function () {
      var $ = cheerio.load(html);
      var vnode = $('.content > .left > .nr > .xhlist > dd');
      var imgLength = $('.content > .left > .nr > .xhlist > dd').length;
      for (var i = 0; i < imgLength; i++) {
        var imgurl = vnode[i].children[2].attribs.src;
        var lastadress = vnode[i].children[2].attribs.src.split('.')[3];
        var filename = vnode[i].children[0].data + '.'+ lastadress;
        savedContent(imgurl, filename);
      }
    });

  }).on('error', function (err) {
    console.log(err);
  });
}
//在本地存储所爬取内容
function savedContent(imgurl, filename) {
  var streaml = fs.createWriteStream('./biedoule/' + filename);
  http.get(imgurl, function (res) {
    res.pipe(streaml);
    console.log(filename);
  })
}